﻿using System.Threading;
using System.Threading.Tasks;
using UpperComputer.Application;
using UpperComputer.WPF.Entry.Common;

namespace UpperComputer.WPF.Entry.ViewModels
{
    public class RoleOperationViewModel : OperationViewModel
    {
        private readonly IBaseRoleService _roleService;

        private BaseRoleResultDto _role = new BaseRoleResultDto();
        public BaseRoleResultDto Role
        {
            get => _role;
            set => SetProperty(ref _role, value);
        }

        public RoleOperationViewModel(IBaseRoleService roleService, long id)
        {
            _roleService = roleService;
            Id = id;
        }

        protected override async Task LoadAsync(object parameter, CancellationToken cancellationToken)
        {
            if (!IsAdd)
            {
                Role = await _roleService.Get(Id, cancellationToken);
            }
        }

        protected override async Task OkAsync(object parameter, CancellationToken cancellationToken)
        {
            if (!IsValidated || !Role.IsValidated)
            {
                return;
            }
            await TryExecuteCommandAysnc(async cancellationToken =>
            {
                _ = IsAdd ? await _roleService.Post(Role, cancellationToken) : await _roleService.Put(Role, cancellationToken);
                CloseRootDialog(true);
            }, cancellationToken);
        }
    }
}